package com.suneee.refund.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;

import com.sun.jndi.cosnaming.IiopUrl.Address;
import com.suneee.core.error.ErrorUtils;
import com.suneee.refund.address.bean.RefundAddress;
import com.suneee.refund.entity.RefundApply;
import com.suneee.refund.entity.RefundComment;
import com.suneee.refund.params.RefundParams;
import com.suneee.resources.ProductError;
import com.taobao.api.domain.AddressResult;
import com.taobao.api.domain.Refund;
import com.taobao.api.domain.RefundMessage;
import com.taobao.api.request.LogisticsAddressModifyRequest;

public class ReflectUtil {

	/**
	 * 把源对象非空属性赋值到目标对象，源对象与目标对象必须有相同的属性名，
	 * 并提供相应的get、set方法(源对象与目标对象属于同一类型)
	 * @param model 源对象
	 * @param target 目标对象
	 */
	public static void reflect(Object model,Object target){
		// 获取实体类的所有属性，返回Field数组
		Field[] field = model.getClass().getDeclaredFields();
		// 遍历所有属性  
		for(int i = 0;i < field.length;i++){
			// 获取属性的名字 
			String name = field[i].getName();
			// 将属性的首字符大写，方便构造get，set方法  
			name = name.substring(0, 1).toUpperCase() + name.substring(1);
			Method getMethod;
			try {
				getMethod = model.getClass().getMethod("get" + name);
				if(getMethod.invoke(model) != null){
					Method setMethod = target.getClass().getMethod("set" + name, field[i].getType());
					setMethod.invoke(target, getMethod.invoke(model));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
			} 
			
		}
	}
	
	/**
	 * 把源对象非空属性赋值到目标对象，源对象与目标对象必须有相同的属性名，
	 * 并提供相应的get、set方法(源对象与目标对象属于不是同一类型)
	 * @param model 源对象，天猫api提供
	 * @param target 目标对象
	 */
	public static void tmallObjectreflect(Object model,Object target){
		// 获取实体类的所有属性，返回Field数组
		Field[] field = model.getClass().getDeclaredFields();
		Field[] targetField = target.getClass().getDeclaredFields();
		// 遍历所有属性  
		for(int i = 0;i < field.length;i++){
			// 获取属性的名字 
			String name = field[i].getName();
			Field tempField = null;
			for(Field f : targetField){
				if(f.getName().equals(name)){
					tempField = f;
					break;
				}
			}
			if(tempField == null)
				continue;
			// 将属性的首字符大写，方便构造get，set方法  
			name = name.substring(0, 1).toUpperCase() + name.substring(1);
			Method getMethod;
			try {
				getMethod = model.getClass().getMethod("get" + name);
				if(getMethod.invoke(model) != null){
					Method setMethod = target.getClass().getMethod("set" + name, tempField.getType());
					String typeName = tempField.getType().getName();
					if(typeName.equals("java.lang.String"))
						setMethod.invoke(target, String.valueOf(getMethod.invoke(model)));
					if(typeName.equals("java.lang.Integer"))
						setMethod.invoke(target, Integer.valueOf(String.valueOf(getMethod.invoke(model))));
					if(typeName.equals("java.lang.Long"))
						setMethod.invoke(target, Long.valueOf(String.valueOf(getMethod.invoke(model))));
					if(typeName.equals("java.lang.Boolean"))
						setMethod.invoke(target, Boolean.valueOf(String.valueOf(getMethod.invoke(model))));
					if(typeName.equals("java.lang.Float"))
						setMethod.invoke(target, Float.valueOf(String.valueOf(getMethod.invoke(model))));
					//java.sql.Timestamp
					if(typeName.equals("java.sql.Timestamp")){
						Date date = (Date)getMethod.invoke(model);
						setMethod.invoke(target, new Timestamp(date.getTime()));
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
			} 
			
		}
	}
	
	public static void tmallRefundValueChanger(Refund tRefund,RefundApply apply){
		if(tRefund.getRefundId() != null)
			apply.setRefundId(String.valueOf(tRefund.getRefundId()));
		
		if(tRefund.getTid() != null)
			apply.setTid(String.valueOf(tRefund.getTid()));
		
		apply.setShippingType(tRefund.getShippingType());
		
		if(tRefund.getCsStatus() != null)
			apply.setCsStatus(String.valueOf(tRefund.getCsStatus()));
		
		if(tRefund.getAdvanceStatus() != null)
			apply.setAdvanceStatus(String.valueOf(tRefund.getAdvanceStatus()));
		
		if(tRefund.getSplitTaobaoFee() != null)
			apply.setSplitTaobaoFee(Float.valueOf(String.valueOf(tRefund.getSplitTaobaoFee())));
		
		if(tRefund.getSplitSellerFee() != null)
			apply.setSplitSellerFee(Float.valueOf(String.valueOf(tRefund.getSplitSellerFee())));
		
		if(tRefund.getOid() != null)
			apply.setOid(String.valueOf(tRefund.getOid()));
		
		apply.setAlipayNo(tRefund.getAlipayNo());
		
		if(tRefund.getTotalFee() != null)
			apply.setTotalFee(Float.valueOf(String.valueOf(tRefund.getTotalFee())));
		
		apply.setBuyerNick(tRefund.getBuyerNick());
		
		if(tRefund.getCreated() != null)
			apply.setCreated(new Timestamp(tRefund.getCreated().getTime()));
		
		if(tRefund.getModified() != null)
			apply.setModified(new Timestamp(tRefund.getModified().getTime()));
		
		apply.setOrderStatus(tRefund.getOrderStatus());
		
		apply.setStatus(tRefund.getStatus());
		
		apply.setHasGoodReturn(tRefund.getHasGoodReturn());
		
		if(tRefund.getRefundFee() != null)
			apply.setRefundFee(Float.valueOf(tRefund.getRefundFee()));
		
		if(tRefund.getPayment() != null)
			apply.setPayment(Float.valueOf(tRefund.getPayment()));
		
		apply.setReason(tRefund.getReason());
		
		apply.setDescription(tRefund.getDesc());
		
		apply.setTitle(tRefund.getTitle());
		
		if(tRefund.getPrice() != null)
			apply.setPrice(Float.valueOf(String.valueOf(tRefund.getPrice())));
		
		if(tRefund.getNum() != null)
		{
			apply.setGoodsNum(Integer.valueOf(String.valueOf(tRefund.getNum())));
			//apply.setRefundNums(Integer.valueOf(String.valueOf(tRefund.getNum())));
		}
		
		if(tRefund.getGoodReturnTime() != null)
			apply.setGoodReturnTime(new Timestamp(tRefund.getGoodReturnTime().getTime()));
		
		apply.setCompanyName(tRefund.getCompanyName());
		
		apply.setSid(tRefund.getSid());
		
		apply.setAddress(tRefund.getAddress());
		
		if(tRefund.getNumIid() != null)
			apply.setNumIid(String.valueOf(tRefund.getNumIid()));
		
		apply.setRefundPhase(tRefund.getRefundPhase());
		
		if(tRefund.getRefundVersion() != null)
			apply.setRefundVersion(String.valueOf(tRefund.getRefundVersion()));
		
		apply.setSkuStr(tRefund.getSku());
		
		apply.setAttribute(tRefund.getAttribute());
		
		apply.setOuterId(tRefund.getOuterId());
		
		apply.setOperationContraint(tRefund.getOperationContraint());
		
		apply.setSellerName(tRefund.getSellerNick());
		
		apply.setCreatedAt(new Timestamp(System.currentTimeMillis()));
		
		apply.setGoodStatus(tRefund.getGoodStatus());
		
		apply.setProcessStatus(RefundParams.PROCESS_STATUS_INIT);
		if(tRefund.getHasGoodReturn())
			apply.setAfterSaleType(RefundParams.AFTER_SALE_TYPE_REFUND_REFUND_GOODS);
		else
			apply.setAfterSaleType(RefundParams.AFTER_SALE_TYPE_REFUND_MONEY);
		apply.setRefundResult(RefundParams.PROCESS_STATUS_INIT);
		
		apply.setIsNoticeStock("0");
		apply.setIsNoticeRefund("0");
		
	}
	
	public static void refundMessageValueChanger(RefundMessage msg,RefundComment comment){
		comment.setRefundId(String.valueOf(msg.getRefundId()));
		comment.setOwnerId(Long.valueOf(String.valueOf(msg.getOwnerId())).intValue());
		comment.setOwnerNick(msg.getOwnerNick());
		comment.setContent(msg.getContent());
		if(msg.getPicUrls() != null && !msg.getPicUrls().isEmpty()){
			StringBuffer sbf = new StringBuffer();
			for(int i = 0;i < msg.getPicUrls().size();i++){
				if(i != msg.getPicUrls().size() - 1)
					sbf.append(msg.getPicUrls().get(i).getUrl()).append(",");
				else
					sbf.append(msg.getPicUrls().get(i).getUrl());
			}
			comment.setPicUrls(sbf.toString());
		}
		comment.setCreated(new Timestamp(msg.getCreated().getTime()));
		comment.setMessageType(msg.getMessageType());
		comment.setRefundPhase(msg.getRefundPhase());
		comment.setOwnerRole(msg.getOwnerRole());
		comment.setCreatedAt(new Timestamp(System.currentTimeMillis()));
	}
	
	/**
	 * 转换对象方法：调用天猫接口返回参数对象 转换成 中台退货地址对象 
	 * @param rfdAddress
	 * @param result
	 */
	public static void tmallChangeAddress(AddressResult result,RefundAddress rfdAddress)
	{
		if(null == rfdAddress || null == result)
		{
			throw ErrorUtils.wrap(ProductError.TMALL_HX_FAIL,"调用天猫新增退货地址接口参数错误");
		}
		rfdAddress.setId(result.getContactId());
		rfdAddress.setName(result.getContactName());
		rfdAddress.setReceiverState(result.getProvince());
		rfdAddress.setReceiverCity(result.getCity());
		rfdAddress.setReceiverDistrict(result.getCountry());
		rfdAddress.setReceiverAddress(result.getAddr());
		rfdAddress.setPostCode(result.getZipCode());
		rfdAddress.setPhone(result.getMobilePhone());
		rfdAddress.setCompany(result.getSellerCompany());
		rfdAddress.setAddressRemark(result.getMemo());
		rfdAddress.setDefaults(result.getCancelDef());
		rfdAddress.setCreatedAt(new Timestamp(new Date().getTime()));
		Timestamp tamp = new Timestamp(System.currentTimeMillis());
		rfdAddress.setUpdateAt(tamp);
	}
	
	/**
	 * 转换对象方法：将中台退货地址对象转换成 调用天猫接口入参对象
	 * @param rfdAddress
	 * @param result
	 */
	public static void ztEPtoTmallAddress(RefundAddress rfdAddress,LogisticsAddressModifyRequest result)
	{
		if(null == rfdAddress || null == result)
		{
			throw ErrorUtils.wrap(ProductError.TMALL_HX_FAIL,"调用天猫修改退货地址接口参数错误");
		}
		result.setContactId(rfdAddress.getId());
		result.setContactName(rfdAddress.getName());
		result.setProvince(rfdAddress.getReceiverState());
		result.setCity(rfdAddress.getReceiverCity());
		result.setCountry(rfdAddress.getReceiverDistrict());
		result.setAddr(rfdAddress.getReceiverAddress());
		result.setZipCode(rfdAddress.getPostCode());
		result.setMobilePhone(rfdAddress.getPhone());
		result.setSellerCompany(rfdAddress.getCompany());
		result.setMemo(rfdAddress.getAddressRemark());
		if(rfdAddress.getDefaults())
		{
			result.setCancelDef(true);
			result.setGetDef(true);
		}
		else
		{
			result.setCancelDef(false);
			result.setGetDef(false);
		}
		
	}
}
